<template>
    <Modal
            v-model="pictureVisible"
            :mask-closable="false"
            :title="!formItem.id ? '新增成本中心用户' : isDetail ? '查看成本中心用户' : '编辑成本中心用户'">
        <Form class="formList" ref="centerUserForm" :model="formItem" :label-width="130" :rules="validateMalfunction" :disabled="isDetail">
            <FormItem label="工厂：" prop="company">
                <Select
                        v-model="formItem.company"
                        clearable
                        :placeholder="`${$t('common.selectInfo')}`"
                >
                    <Option v-for="(item,index) of factoryList" :value="item.id" :key="index">{{ item.name }}</Option>
                </Select>
            </FormItem>
            <FormItem label="成本中心：" prop="costCenter">
<!--                <Select-->
<!--                        v-model="formItem.ktextName"-->
<!--                        filterable-->
<!--                        clearable-->
<!--                        placeholder="请选择成本中心"-->
<!--                        :remote-method="getSpecificationList"-->
<!--                        :loading="searchLoading"-->
<!--                >-->
<!--                    <Option v-for="(item,index) of specificationList" :value="item.ktextName" :key="index">{{ item.ktextName }}</Option>-->
<!--                </Select>-->
              <Input type="number" v-model="formItem.costCenter" placeholder="请录入成本中心"/>
            </FormItem>
          <FormItem label="成本中心名称：" prop="costCenterName">
            <Input v-model="formItem.costCenterName" placeholder="请录入成本中心名称"/>
          </FormItem>
            <FormItem label="设备管理员：" prop="ktextUserName">
                <Select
                        v-model="formItem.ktextUserName"
                        filterable
                        clearable
                        :placeholder="`${$t('common.selectInfo')}`"
                        :remote-method="getDeviceNameList"
                        :loading="searchUserLoading"
                >
                    <Option v-for="(item,index) of deviceNameList" :value="item.ktextUserName" :key="index">{{ item.ktextUserName }}</Option>
                </Select>
            </FormItem>
        </Form>
        <div slot="footer">
            <Button type="default"  @click="handleCancel">{{$t('common.Cancle')}}</Button>
            <Button type="primary" :loading="loading" v-show="!isDetail"  @click="handleOk">{{$t('maintenance.Confirmed')}}</Button>
        </div>
    </Modal>
</template>

<script>
    export default {
        name: "centerUserModal",
        data() {
            return {
                id: '',
                searchLoading: false,
                searchUserLoading: false,
                isDetail: false,
                pictureVisible: false,
                loading: false,
                formItem: {
                    company: '',
                     costCenter:'',
                     costCenterName: '',
                    ktextUserName: '',
                },
                validateMalfunction: {
                    company: [
                        { required: true, message: '请选择工厂', trigger: 'change' }
                    ],
                  costCenter: [
                        { required: true, message: '请选择成本中心', trigger: 'blur' }
                    ],
                  costCenterName: [
                    { required: true, message: '请选择成本中心名称', trigger: 'blur' }
                  ],
                    ktextUserName: [
                        { required: true, message: '请选择设备管理员', trigger: 'change' }
                    ],
                },
                factoryList: [],
                specificationList: [],
                deviceNameList: []
            }
        },
        watch: {
            formItem: {
                handler(newValue) {
                    console.log(newValue)
                },
                immediate: true
            }
        },
        created() {
            this.getCompanyList()
        },
        methods: {
            /**************获取相关下拉数据列表*************/
            getCompanyList() {
                this.axios({
                    method: 'get',
                    url: '/basic/company/getCompanyListByUser',
                    params: {}
                }).then(res => {
                    if (res.code === 200) {
                        let arr = res.data.map(item => {
                            return {
                                ...item,
                                id: item.id.toString()
                            }
                        })
                        this.factoryList = arr
                    } else {
                        this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                    }
                })
            },
            show(type, record, isDetail) {
                this.pictureVisible = true
                console.log(type);
                if (type === 'add') {
                    this.formItem.id = '';
                    this.isDetail = false;
                    this.formItem.company = '';
                    this.formItem.costCenter = '';
                    this.formItem.costCenterName = '';
                    this.formItem.ktextUserName = '';
                }else {
                    this.isDetail = isDetail || false
                    this.getDetail(record.id)
                }
            },
            async getDetail(id) {
                await this.axios({
                    method: 'get',
                    url: '/dms/dmsUserCostCenter/detail',
                    params: {
                        id
                    },
                }).then(res => {
                    
                    if (res.code == 200) {
                        this.formItem = res.data
                        this.formItem.id = res.data.id
                        this.formItem.company = res.data.company ? res.data.company.toString() : ''
                        // this.formItem.ktextName = res.data.costCenter + '-' + res.data.costCenterName
                        this.formItem.costCenter = res.data.costCenter
                        this.formItem.costCenterName = res.data.costCenterName
                        this.formItem.ktextUserName = res.data.moveInAdminNo + '----' + res.data.moveInAdminName
                        //this.getSpecificationList(res.data.costCenter)
                        this.getDeviceNameList(res.data.moveInAdminNo)
                        // this.formItem.fileUrl = res.data.fileUrl
                        // this.formItem.fileName = res.data.fileName
                        // this.formItem.filePath = res.data.filePath
                    }else {
                        this.$Message.warning(({content: res.msg, duration: 6, closable: true}))
                    }
                }).catch(() => {});
            },
            getSpecificationList(query) {
                let companyCode = this.factoryList.filter(item => item.id === this.formItem.company)[0].code
                if (query !== '') {
                    this.searchLoading = true
                    this.axios({
                        method: 'get',
                        url: '/tms/tmApplyUse/getCostCenter',
                        params: {
                            companyCode,
                            costCenter: query
                        }
                    }).then(res => {
                        if (res.code === 200) {
                            this.specificationList = res.data.map(item => {
                                return {
                                    ...item,
                                    ktextName: item.kostl + '-' + item.ktext
                                }
                            })
                        } else {
                            this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                        }
                    }).finally(() => {
                        this.searchLoading = false
                    })
                }else {
                    this.specificationList = []
                }
            },
            getDeviceNameList(query) {
                if (query !== '') {
                    this.searchUserLoading = true
                    this.axios({
                        method: 'get',
                        url: '/basic/user/searchOAUser',
                        params: {
                            key: query,
                        }
                    }).then(res => {
                        if (res.code === 200) {
                            this.deviceNameList = res.data.map(item => {
                                return {
                                    ...item,
                                    ktextUserName: item.empno + '----' + item.username,
                                }
                            })
                        } else {
                            this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                        }
                    }).finally(() => {
                        this.searchUserLoading = false
                    })
                }else {
                    this.deviceNameList = []
                }
            },
            handleOk() {
                let { id, company, ktextUserName,costCenter,costCenterName } = this.formItem
                let moveInAdminNo,moveInAdminName = ''
                // if (ktextName) {
                //     let index = ktextName.indexOf('-')
                //     costCenter = ktextName.substr(0,index)
                //     costCenterName = ktextName.substr(index+1,ktextName.length-1)
                //     console.log(costCenter,costCenterName)
                // }
                if (ktextUserName) {
                    let index = ktextUserName.indexOf('----')
                    moveInAdminNo = ktextUserName.substr(0,index)
                    moveInAdminName = ktextUserName.substr(index+4,ktextUserName.length-1)
                    console.log(moveInAdminNo,moveInAdminName)
                }
                this.$refs.centerUserForm.validate((valid) => {
                    if (valid) {
                        this.loading = true
                        if (!this.formItem.id) {
                            let params = {
                                company,
                                costCenter,
                                costCenterName,
                                moveInAdminNo,
                                moveInAdminName
                            }
                            this.axios({
                                method: 'post',
                                url: '/dms/dmsUserCostCenter/add',
                                data: params
                            }).then(res => {
                                
                                if (res.code === 200) {
                                    this.pictureVisible = false
                                    this.loading = false
                                    this.$Message.success('新增成功！')
                                    this.$refs.centerUserForm.resetFields();
                                    this.$emit('refresh')
                                }else {
                                    this.pictureVisible = false
                                    this.loading = false
                                    this.$Message.error(({content: res.msg, duration: 6, closable: true}))
                                    this.$refs.centerUserForm.resetFields();
                                }
                            })
                        }else {
                            let params = {
                                id,
                                company,
                                costCenter,
                                costCenterName,
                                moveInAdminNo,
                                moveInAdminName
                            }
                            this.axios({
                                method: 'put',
                                url: '/dms/dmsUserCostCenter/edit',
                                data: params
                            }).then(res => {
                                
                                if (res.code === 200) {
                                    this.pictureVisible = false
                                    this.loading = false
                                    this.$Message.success('编辑成功！')
                                    this.$refs.centerUserForm.resetFields();
                                    this.$emit('refresh')
                                }else {
                                    this.pictureVisible = false
                                    this.loading = false
                                    this.$Message.error(({content: res.msg, duration: 6, closable: true}))
                                    this.$refs.centerUserForm.resetFields();
                                }
                            })
                        }
                    }
                })
            },
            handleCancel() {
                this.$refs.centerUserForm.resetFields();
                this.pictureVisible = false
            }
        }
    }
</script>

<style scoped>

</style>
